package com.quectel.core.module.partybuildingactivity.service.impl;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.func.LambdaUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.base.Preconditions;
import com.quectel.constant.core.partybuilding.PartyBuildingMeetingConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.partybuilding.dto.PartyOrganizationDto;
import com.quectel.core.module.partybuilding.dto.PartyPersonDto;
import com.quectel.core.module.partybuilding.service.PartyOrganizationService;
import com.quectel.core.module.partybuildingactivity.dao.PartyBuildingActivityDao;
import com.quectel.core.module.partybuildingactivity.dao.PartyBuildingActivityPersonJoinBindingDao;
import com.quectel.core.module.partybuildingactivity.dto.PartyBuildingActivityDto;
import com.quectel.core.module.partybuildingactivity.dto.PartyBuildingActivityPersonJoinBindingDto;
import com.quectel.core.module.partybuildingactivity.entity.PartyBuildingActivityEntity;
import com.quectel.core.module.partybuildingactivity.entity.PartyBuildingActivityPersonJoinBindingEntity;
import com.quectel.core.module.partybuildingactivity.service.PartyBuildingActivityPersonJoinBindingService;
import com.quectel.core.module.partybuildingactivity.service.PartyBuildingActivityService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
/**
 *
 * @author bob
 * @email bob.yu@quectel.com
 * @date 2023/05/24 11:38
 */
@DubboService
public class PartyBuildingActivityServiceImpl implements PartyBuildingActivityService {

    private static final Logger LOGGER = LoggerFactory.getLogger(PartyBuildingActivityServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> PARTY_BUILDING_ACTIVITY_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "PARTY_BUILDING_ACTIVITY_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<PartyBuildingActivityDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(PARTY_BUILDING_ACTIVITY_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };

    @Autowired
    private PartyBuildingActivityDao partyBuildingActivityDao;
    @Autowired
    private PartyBuildingActivityPersonJoinBindingService activityPersonJoinBindingService;
    @Autowired
    private PartyBuildingActivityPersonJoinBindingDao activityPersonJoinBindingDao;
    @Autowired
    private PartyOrganizationService partyOrganizationService;


    /**
     * save or update
     *
     * @param partyBuildingActivityDto
     */
    @Override
    public Long saveOrUpdate(PartyBuildingActivityDto partyBuildingActivityDto) {

        // 报名提醒时间
        if(!PartyBuildingMeetingConstants.RemindType.NO_NEED.getType().equals(partyBuildingActivityDto.getJoinRemindType())){
            PartyBuildingMeetingConstants.RemindType byType = PartyBuildingMeetingConstants.RemindType.getByType(partyBuildingActivityDto.getJoinRemindType());
            Preconditions.checkNotNull(byType);
            DateTime dateTime = DateUtil.offsetMinute(partyBuildingActivityDto.getJoinStartTime(), -byType.getOffsetTime());
            partyBuildingActivityDto.setJoinRemindTime(dateTime);
        }

        // 参与提醒时间
        if(!PartyBuildingMeetingConstants.RemindType.NO_NEED.getType().equals(partyBuildingActivityDto.getActivityRemindType())){
            PartyBuildingMeetingConstants.RemindType byType = PartyBuildingMeetingConstants.RemindType.getByType(partyBuildingActivityDto.getActivityRemindType());
            Preconditions.checkNotNull(byType);
            DateTime dateTime = DateUtil.offsetMinute(partyBuildingActivityDto.getActivityStartTime(), -byType.getOffsetTime());
            partyBuildingActivityDto.setActivityRemindTime(dateTime);
        }

        if (partyBuildingActivityDto.getId() == null){
            Long id = save(partyBuildingActivityDto);
            partyBuildingActivityDto.setId(id);
        }else {
            updateById(partyBuildingActivityDto);
        }

        // 删除人员绑定关系
        activityPersonJoinBindingDao.delete(new LambdaQueryWrapper<PartyBuildingActivityPersonJoinBindingEntity>()
                .eq(PartyBuildingActivityPersonJoinBindingEntity::getPartyBuildingActivityId, partyBuildingActivityDto.getId()));

        // 绑定下党员信息到中间表
        for (PartyPersonDto personDto : partyBuildingActivityDto.getPartyPersonList()) {
            PartyBuildingActivityPersonJoinBindingDto activityPersonJoinBindingDto = new PartyBuildingActivityPersonJoinBindingDto();
            activityPersonJoinBindingDto.setId(Snowflake.nextId());
            activityPersonJoinBindingDto.setPartyBuildingActivityId(partyBuildingActivityDto.getId());
            activityPersonJoinBindingDto.setPartyPersonId(personDto.getId());
            activityPersonJoinBindingService.save(activityPersonJoinBindingDto);
        }
        return partyBuildingActivityDto.getId();
    }

    @Override
    public PartyBuildingActivityDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                PARTY_BUILDING_ACTIVITY_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public PartyBuildingActivityDto selectById(Long id){
            PartyBuildingActivityEntity entity = partyBuildingActivityDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity,PartyBuildingActivityDto.class));
    }

    @Override
    public List<PartyBuildingActivityDto> queryList(Map<String,Object> params){
        List<PartyBuildingActivityEntity> list = partyBuildingActivityDao.queryList(params);
        List<PartyBuildingActivityDto> result =  CopyUtils.copyList(list,PartyBuildingActivityDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    /**
     * 查询列表 不对内部对象进行填充速度较快
     *
     * @param params
     * @return
     */
    @Override
    public List<PartyBuildingActivityDto> queryListWithoutPadding(Map<String, Object> params) {
        List<PartyBuildingActivityEntity> list = partyBuildingActivityDao.queryList(params);
        return CopyUtils.copyList(list, PartyBuildingActivityDto.class);
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属园区等
     *
     * @param dto
     * @return
     */
    private PartyBuildingActivityDto paddingField(PartyBuildingActivityDto dto){
        if (dto != null){
            if (dto.getPartyId()!=null){
                PartyOrganizationDto organizationDto = partyOrganizationService.selectCacheById(dto.getPartyId());
                if (organizationDto!=null){
                    dto.setPartyName(organizationDto.getName());
                }
            }

            Map<String, Object> sqlMap = new HashMap<>();
            sqlMap.put(LambdaUtil.getFieldName(PartyBuildingActivityPersonJoinBindingDto::getPartyBuildingActivityId), dto.getId());
            int totalJoinCount = activityPersonJoinBindingService.queryTotal(sqlMap);
            dto.setTotalJoinCount(totalJoinCount);

            // 已报名 1
            sqlMap.put(LambdaUtil.getFieldName(PartyBuildingActivityPersonJoinBindingDto::getJoinStatus), PartyBuildingMeetingConstants.JoinStatus.JOIN.getStatus());
            int joinCount = activityPersonJoinBindingService.queryTotal(sqlMap);
            sqlMap.remove(LambdaUtil.getFieldName(PartyBuildingActivityPersonJoinBindingDto::getJoinStatus));
            dto.setJoinCount(joinCount);

            // 已签到 1
            sqlMap.put(LambdaUtil.getFieldName(PartyBuildingActivityPersonJoinBindingDto::getSignStatus), PartyBuildingMeetingConstants.SignStatus.SIGN.getStatus());
            int signCount = activityPersonJoinBindingService.queryTotal(sqlMap);
            dto.setSignCount(signCount);
        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params){
        return partyBuildingActivityDao.queryTotal(params);
    }

    @Override
    public Long save(PartyBuildingActivityDto dto){
        PartyBuildingActivityEntity entity = CopyUtils.copyObj(dto,PartyBuildingActivityEntity.class);
        entity.setId(Snowflake.nextId());
        partyBuildingActivityDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(PartyBuildingActivityDto dto){
        PartyBuildingActivityEntity entity = CopyUtils.copyObj(dto,PartyBuildingActivityEntity.class);

        partyBuildingActivityDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void updateAllColumnById(PartyBuildingActivityDto dto) {
       PartyBuildingActivityEntity entity = CopyUtils.copyObj(dto,PartyBuildingActivityEntity.class);

       MyBatisPlusUtils.updateAllColumnById(entity, partyBuildingActivityDao);

       CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id){

        CLEAR_CACHE_FUNC.accept(selectById(id));

        partyBuildingActivityDao.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids){
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
